package mysrpringboot.springboot.controller;

import mysrpringboot.springboot.Dao.OrderDao;
import mysrpringboot.springboot.Service.SellService;
import mysrpringboot.springboot.redisConfig.RedisLock;
import mysrpringboot.springboot.rocketmq.Myconsumer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/order")
public class Controller {
    @Autowired
    private RedisTemplate<String, String> redis;

    @Autowired
    private RedisLock redisLock;
    @Autowired
    private SellService SellService;
    @Autowired
    private SellService sellService;
    @Autowired
    private Myconsumer myconsumer;
    @Autowired
    private OrderDao orderDao;
    @RequestMapping("/miaosha")
    public String miaosha() throws MQClientException {
        int numredis = SellService.findNum();
        if(numredis==0){
            return "仓库没库存了";
        }else{
            redisLock.lock();
        }

        List consumer = myconsumer.consumer();
        for (int i=0;i<consumer.size();i++){
            //放入redis过期key
            sellService.expirsePay(consumer.get(i).toString());
        }
        int size = consumer.size();
        int num = sellService.findNum();
        //库存数
       int nums = num - size;
       //更新库存数
        orderDao.update(nums);
      //更新缓存数
        sellService.updateNum(nums);
        return "你已秒到商品，请及时支付";
    }

    @RequestMapping("/pay")
    public String pay(String orderId){
        return this.sellService.findkey(orderId);
    }
}
